package org.example.threadorder;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.Sleeper;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * @author zhengdp
 * @Description 线程顺序控制(Park & UnPark)
 * @Date 2022/11/9 22:24
 * @Created by zhengdp
 */
@Slf4j(topic = "c.ThreadOrderParkUnPark2")
public class ThreadOrderParkUnPark2 {

    static Thread t1;
    static Thread t2;
    static Thread t3;
    public static void main(String[] args) {
        ParkUnPark pk = new ParkUnPark(5);
        t1 = new Thread(() -> {
            pk.print("a",t2);
        },"t1");
        t2 = new Thread(() -> {
            pk.print("b",t3);
        },"t2");
        t3 = new Thread(() -> {
            pk.print("c",t1);
        },"t3");
        t1.start();
        t2.start();
        t3.start();

        log.info("开始运行...");
        LockSupport.unpark(t1);
    }
}

@AllArgsConstructor
class ParkUnPark {
    private int loopNumber;

    /**
     *  park 方法针对的是当前线程，所以不需要传入当前线程
     * @param str 输出的内容
     * @param next 需要唤醒的下一个线程
     */
    public void print(String str,Thread next){
        for( int i = 0; i < loopNumber ; i++ ){
            LockSupport.park();
            System.out.print(str);
            // 唤醒下一个线程
            LockSupport.unpark(next);
        }
    }
}
